package com.fs.system.web.controller.common;

import com.fs.common.annotation.Log;
import com.fs.common.core.pojo.SysUser;
import com.fs.common.core.vo.AjaxResult;
import com.fs.common.core.vo.LoginBody;
import com.fs.common.core.vo.LoginUser;
import com.fs.system.service.LoginService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 这是登录接口
 */

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    AjaxResult ajaxResult = AjaxResult.success();
    @PostMapping("/login")
    //ResponseEntity<LoginUser>
    public AjaxResult login(@RequestBody LoginUser loginUser, HttpServletResponse res){
        String uuid = loginService.generateToken(loginUser);
        String token = Jwts.builder()
                .setSubject("LOGIN")
                .claim("uuid",uuid)
                .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) // 设置过期时间为30分钟
                .signWith(SignatureAlgorithm.HS256, "HUSE")
                .compact();
        loginUser.setToken(uuid);
        loginService.saveToRedis(loginUser);
        res.setHeader("Authorization","Bearer" + token);
        ajaxResult.put("msg","登录成功");
        return ajaxResult;
    }


    @PostMapping("/renewToken")
    public Map<String, String> refresh(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 从请求头中获取旧的JWT Token
            String oldToken = request.getHeader("Authorization").replace("Bearer ", "");

            // 解析旧的JWT Token，获取UUID
            String uuid = Jwts.parser()
                    .setSigningKey("HUSE")
                    .parseClaimsJws(oldToken)
                    .getBody()
                    .get("uuid", String.class);

            // 根据UUID从Redis中获取LoginUser对象
            LoginUser loginUser = loginService.parserUserInfoByJwt(uuid);

            // 更新Redis中LoginUser对象的过期时间
            loginService.updateToken(uuid);

            // 生成新的JWT Token
            String newToken = Jwts.builder()
                    .setSubject("LOGIN")
                    .claim("uuid", uuid)
                    .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) // 过期时间为------------------------>30分钟
                    .signWith(SignatureAlgorithm.HS256, "HUSE")
                    .compact();

            // 将新的JWT Token返回给前端
            response.setHeader("Authorization", "Bearer " + newToken);

            // 返回成功信息
            Map<String, String> result = new HashMap<>();
            result.put("message", "刷新成功");
            return result;
        } catch (ExpiredJwtException e) {
            // 如果解析过程中发现Token已过期，返回错误信息
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "您的的的Token已过期");
            return null;
        }
    }



}
